﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScheduleDemo
{
    public class JobService
    {
        StdSchedulerFactory? _schedulerFactory;
        IScheduler? _scheduler;

        public async void Start()
        {
            _schedulerFactory = new StdSchedulerFactory();
            _scheduler = await _schedulerFactory.GetScheduler();
            await _scheduler.Start();

            var job1 = JobBuilder.Create<每分钟第50秒任务>().Build();
            var job1Trigger = TriggerBuilder.Create()
                .WithIdentity("job1Trigger")
                .WithCronSchedule("50 * * * * ?")
                .Build();

            var job2 = JobBuilder.Create<每5分钟第50秒任务>().Build();
            var job2Trigger = TriggerBuilder.Create()
                .WithIdentity("job2Trigger")
                .WithCronSchedule("50 0/5 * * * ?")
                .Build();

            await _scheduler.ScheduleJob(job1, job1Trigger);
            await _scheduler.ScheduleJob(job2, job2Trigger);
        }

        public async void Stop(CancellationToken cancellationToken)
        {
            if (_scheduler != null && _scheduler.IsStarted)
            {
                await _scheduler.Shutdown(cancellationToken);
            }
        }
    }

    internal class 每分钟第50秒任务 : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine($"每分钟第55秒任务 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            return Task.CompletedTask;
        }
    }

    internal class 每5分钟第50秒任务 : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine($"每5分钟第50秒任务 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            return Task.CompletedTask;
        }
    }
}
